import { ref } from 'vue'
import { defineStore } from 'pinia'
import { ComProjectDatabaseService } from '@/api/module/ComProjectDatabaseApi.js'
import { useGlobalStore } from '@/stores/global.js'



export const useDataBaseInfoStore = defineStore('databaseinfo', () => {

  const globalStore = useGlobalStore();

  const checkedDataBaseInfo=ref([]);

  const cacheTableInfo=ref({})

  const checkTableId=ref("")

  const showTableFieldInfo=ref([])

  const modalAddFieldState=ref(false)



  /**
   * 这是加载database 是数据的方法
   */
  function loadDatabaseInfo(){


    ComProjectDatabaseService.getAllDatabaseInfo({
    projectId:globalStore.checkProjectId
    }).then((data)=>{
      checkedDataBaseInfo.value=data?.data.data;
    })


  }


  /**
   * 这是获取表字段
   * @param tableId
   * @returns {*}
   */
  function getTableFieldInfo(){



      ComProjectDatabaseService.getAllTableFieldInfo({
        tableId:checkTableId.value
      }).then((data)=>{
        /*加入缓存*/
        cacheTableInfo[checkTableId]=data.data.data;

        showTableFieldInfo.value= cacheTableInfo[checkTableId];
      })




  }


  /**
   * 添加表方法
   */
  function addTable(param){

    ComProjectDatabaseService.addDatabaseTable({
      projectId:globalStore.checkProjectId,
      ...param,
    }).then(()=>{
      loadDatabaseInfo()
    })

  }

  // 添加表字段方法
  function addTableField(data){

   console.log("addTableField",{
     tableId:checkTableId.value,
     ...data
   })

    ComProjectDatabaseService.addTableField({
      tableId:checkTableId.value,
      ...data
    }).then(()=>{

      getTableFieldInfo();
      modalAddFieldState.value=false;


    }).catch()


  }

  // 删除表字段信息
  function deleteTableField(data){

    console.log(data)
    ComProjectDatabaseService.deleteTableField({
      fieldId:data.id
    }).then(()=>{


      getTableFieldInfo();

    }).catch()

  }


  // 删除表
  function deleteTable(data){

 console.log(data);
    ComProjectDatabaseService.deleteTable({
      tableId:data.id
    }).then(()=>{

      loadDatabaseInfo();

    }).catch()

  }

  return { checkedDataBaseInfo,loadDatabaseInfo,addTable,cacheTableInfo,getTableFieldInfo,checkTableId,addTableField,showTableFieldInfo,modalAddFieldState,deleteTableField,deleteTable}
})
